package com.sunday.aomi.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.sunday.common.base.BaseFragment;
import com.sunday.common.imageselector.MultiImageSelectorActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ImageUtils;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.utils.UploadUtils;
import com.sunday.common.widgets.CircleImageView;
import com.sunday.aomi.R;
import com.sunday.aomi.base.BaseApp;
import com.sunday.aomi.ui.mine.address.AddressListActivity;
import com.sunday.aomi.ui.mine.SettingActivity;
import com.sunday.aomi.ui.order.BuyOrderListActivity;
import com.sunday.aomi.ui.product.ProductCollectionActivity;
import com.sunday.aomi.widgets.UIAlertEditView;
import com.sunday.member.SessionToken;
import com.sunday.member.entity.Member;
import com.sunday.member.entity.UploadImage;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.app.Activity.RESULT_OK;


/**
 * Created by 刘涛 on 2017/5/27.
 * <p>
 * 大客户我的个人中心
 */

public class MineExtraFragment extends BaseFragment {


    @Bind(R.id.user_logo)
    CircleImageView userLogo;
    @Bind(R.id.shop_mobile)
    TextView shopMobile;
    @Bind(R.id.shop_name)
    TextView shopName;
    @Bind(R.id.gridview)
    GridView gridview;

    private List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
    private SimpleAdapter adapter;
    private int[] icon = {R.mipmap.menu_mine_06, R.mipmap.menu_mine_05,};

    private String[] iconName = {"商品收藏", "地址管理"};

    private Member member;

    public static MineExtraFragment newInstance() {
        MineExtraFragment fragment = new MineExtraFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_mine_extra, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getData();
        initView();
    }

    public List<Map<String, Object>> getData() {
        for (int i = 0; i < icon.length; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("image", icon[i]);
            map.put("text", iconName[i]);
            dataList.add(map);
        }
        return dataList;
    }


    private void initView() {
        String[] from = {"image", "text"};
        int[] to = {R.id.item_image, R.id.item_text};
        adapter = new SimpleAdapter(mContext, dataList, R.layout.layout_mine_menu_item, from, to);
        gridview.setAdapter(adapter);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0://商品收藏
                        intent=new Intent(mContext, ProductCollectionActivity.class);
                        startActivity(intent);
                        break;
                    case 1://收货地址
                        intent = new Intent(mContext, AddressListActivity.class);
                        startActivity(intent);
                        break;
                }
            }
        });

        member = (Member) SharePerferenceUtils.getIns(mContext).getOAuth();
        updateView();


    }

    private void updateView(){
        if (!TextUtils.isEmpty(member.getImage())) {
            Picasso.with(mContext)
                    .load(member.getImage())
                    .error(R.mipmap.ic_default)
                    .resize(130, 130)
                    .into(userLogo);
        }
        shopName.setText("昵称:"+member.getNickName());
        shopMobile.setText(member.getMobile());
    }

    private final static int TYPE_NAME = 1;//修改昵称
    private final static int TYPE_LOGO = 2;//修改头像
    private final static int REQUEST_IMAGE = 0x1111;

    @OnClick({R.id.btn_setting,R.id.menu_order_1,R.id.menu_order_2,R.id.menu_order_3,R.id.check_all_order,
    R.id.layout_user_logo,R.id.shop_name})
    void onClick(View v){
        switch (v.getId()){
            case R.id.btn_setting:
                intent=new Intent(mContext, SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.menu_order_1:
                intent=new Intent(mContext, BuyOrderListActivity.class);
                intent.putExtra("page",0);
                startActivity(intent);
                break;
            case R.id.menu_order_2:
                intent=new Intent(mContext, BuyOrderListActivity.class);
                intent.putExtra("page",1);
                startActivity(intent);
                break;
            case R.id.menu_order_3:
                intent=new Intent(mContext, BuyOrderListActivity.class);
                intent.putExtra("page",2);
                startActivity(intent);
                break;
            case R.id.check_all_order:
                intent=new Intent(mContext, BuyOrderListActivity.class);
                intent.putExtra("page",2);
                startActivity(intent);
                break;
            case R.id.layout_user_logo:
                intent = new Intent(mContext, MultiImageSelectorActivity.class);
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
                startActivityForResult(intent, REQUEST_IMAGE);
                break;
            case R.id.shop_name:
                final UIAlertEditView alertView = new UIAlertEditView(mContext, "修改昵称", "请输入新昵称", "取消", "确定", member.getNickName());
                alertView.show();
                alertView.setClicklistener(new UIAlertEditView.ClickListenerInterface() {
                    @Override
                    public void doLeft() {
                        alertView.dismiss();
                    }

                    @Override
                    public void doRight() {
                        String name = alertView.getContent();
                        if (TextUtils.isEmpty(name)) {
                            ToastUtils.showToast(mContext, "请输入具体名字");
                            return;
                        }
                        saveInfo(name, TYPE_NAME);
                        alertView.dismiss();
                    }
                });
                break;
        }
    }

    private ArrayList<String> mSelectPath = new ArrayList<>();
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_IMAGE:
                mSelectPath.clear();
                mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                if (mSelectPath != null) {
                    String logo = ImageUtils.getCompressImagePath(mSelectPath.get(0));
                    Picasso.with(mContext)
                            .load(new File(logo))
                            .placeholder(R.mipmap.ic_avtar)
                            .error(R.mipmap.ic_avtar)
                            .resize(130, 130)
                            .into(userLogo);
                    uploadImg(UploadUtils.getRequestBody(logo));
                }
                break;
        }
    }

    private void uploadImg(final RequestBody requestBody) {
        showLoadingDialog(0);
        Call<ResultDO<UploadImage>> call
                = MemberClient.getApiAdapter().uploadSingle(requestBody);
        call.enqueue(new Callback<ResultDO<UploadImage>>() {
            @Override
            public void onResponse(Call<ResultDO<UploadImage>> call, Response<ResultDO<UploadImage>> response) {
                dissMissDialog();
                if (response.body() == null || isFinish) {
                    return;
                }
                if (response.body() != null && response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext,"上传成功");
                    String img=response.body().getResult().getHalfPath();
                    saveInfo(img,TYPE_LOGO);
                    updateView();

                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<UploadImage>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, "网络错误");
            }
        });
    }

    private void saveInfo(String str, int type) {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{type == TYPE_NAME ? "nickName" : "image","nonce"};
        String[] str2 = new String[]{str, nonce};
        showLoadingDialog(0);
        Call<ResultDO<Member>> call = null;
        if (type == TYPE_NAME) {
            call = MemberClient.getApiAdapter().updateUserInfo(str, null, null, null, null, null, null, nonce, SignUtil.getSign(str1, str2));
        } else {
            call = MemberClient.getApiAdapter().updateUserInfo(null, null, null, null, str, null, null, nonce, SignUtil.getSign(str1, str2));
        }
        call.enqueue(new Callback<ResultDO<Member>>() {
            @Override
            public void onResponse(Call<ResultDO<Member>> call, Response<ResultDO<Member>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0) {
                    member = response.body().getResult();
                    SharePerferenceUtils.getIns(mContext).saveOAuth(member);
                    BaseApp.getInstance().setMember(member);
                    SessionToken.token = member.getToken();
                    updateView();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Member>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }





    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
